package lvbu.wang.lvbuoperator.http;

import android.content.Context;
import android.util.Log;

import com.qing.library.utils.L;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import lvbu.wang.lvbuoperator.R;
import lvbu.wang.lvbuoperator.bean.JsonMessage;
import lvbu.wang.lvbuoperator.constants.ConstantsValue;
import lvbu.wang.lvbuoperator.core.BaseActivity;
import lvbu.wang.lvbuoperator.engine.IotServerConfig;
import lvbu.wang.lvbuoperator.utils.CommonUtil;


/**
 * Created by DaiQing.Zha on 2016/6/8 0008.
 * Email:1642674371@qq.com
 * Description:
 */
public class IotHttpHelp {

    /**
     * 获取网络数据
     * @param route 请求地址
     * @param params 请求参数
     * @param autoAuthCode 是否需要自动添加autoAuthCode
     * @param context 上下文环境
     * @return 返回请求结果
     */
    public static String getData(String route, Map<String, Object> params, boolean autoAuthCode, Context context) {
        return httpPost(route, params, autoAuthCode, context);
    }


    /**
     * 判断source是否有正确,不正确情况包括：http错误、返回null
     *
     * @param source
     * @return
     */
    public static boolean checkSource(String source) {
        try {
            if (source.equals(JsonMessage.HttpNotFund)) return false;
            if (source.equals(JsonMessage.ResponseWrong)) return false;
            if (source.equals(JsonMessage.FailString)) return false;
            if (source.equals(JsonMessage.MalfError)) return false;
            if (source.equals(JsonMessage.ProtocolError)) return false;
            if (source.equals(JsonMessage.IOError)) return false;
            if (source.equals(JsonMessage.Error)) return false;
            if (source.equals(JsonMessage.Null)) return false;
        } catch (Exception e) {
            // CrashReport.postCatchedException(e);
            return false;
        }
        return true;
    }

    /**
     * 生成motor命令地址的id
     *
     * @param motorId
     * @param sendCode
     * @return
     */
    public static String makeMotorCommandAddressId(long motorId, String sendCode) {
        return motorId + sendCode + new Date().getTime();
    }

    /**
     * 显示source的http消息，配合checkSource使用
     *
     * @param context
     * @param source
     * @return
     */
    public static String source2Message(Context context, String source) {
        if (source.equalsIgnoreCase(JsonMessage.FailString)) return context.getResources().getString(R.string.toast_comm_httpFail);
        if (source.equalsIgnoreCase(JsonMessage.MalfError)) return context.getString(R.string.toast_comm_malformedError);
        if (source.equalsIgnoreCase(JsonMessage.IOError)) return context.getString(R.string.toast_comm_ioError);
        if (source.equalsIgnoreCase(JsonMessage.Error)) return context.getResources().getString(R.string.toast_comm_httpError);
        if (source.equalsIgnoreCase(JsonMessage.Null)) return context.getResources().getString(R.string.toast_comm_httpNull);
        if (source.equalsIgnoreCase(JsonMessage.ResponseWrong)) return context.getResources().getString(R.string.toast_comm_httpResponseWrong);
        if (source.equalsIgnoreCase(JsonMessage.HttpNotFund)) return context.getResources().getString(R.string.toast_comm_httpNotFund);
        return source.replace("\"", "");
    }

    /**
     * 通过get方式获取网络数据
     * @param route
     * @param params
     * @param autoAuthCode
     * @param context
     * @return
     */
    private static String httpPost(String route, Map<String, Object> params, boolean autoAuthCode, Context context) {

        Map<String,Object> mapParams = new HashMap<>();
        if (params != null && params.size() > 0){
            for (String name:params.keySet()){
                String value = String.valueOf(params.get(name));
                mapParams.put(name, value);
            }
        }
        if (autoAuthCode){
            mapParams.put("authCode", getAuthCode(context));
        }
        String urlPath = IotServerConfig.getWsServerRoot() + route;
        Log.e("haha", "httpPost: " + urlPath,null );
//        String urlPath = "http://a.lvbu.co/api/saleProduct/Get_JsonApp_AppVersion_New";s
        Log.e("mainBARCODE","url = " + urlPath);
        String dataString = getRequestData(mapParams, "UTF-8").toString();
        byte[] data = dataString.getBytes();// 获得请求体
        try {
            URL url = new URL(urlPath);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setConnectTimeout(120000); // 设置连接超时时间
            httpURLConnection.setReadTimeout(120000);// 设置读取时间
            httpURLConnection.setDoInput(true); // 打开输入流，以便从服务器获取数据
            httpURLConnection.setDoOutput(true); // 打开输出流，以便向服务器提交数据
            httpURLConnection.setRequestMethod("POST"); // 设置以Post方式提交数据
            httpURLConnection.setUseCaches(false); // 使用Post方式不能使用缓存

            // 设置请求体的类型是文本类型
            httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            // 设置请求体的长度
            httpURLConnection.setRequestProperty("Content-Length", String.valueOf(data.length));

            // 获得输出流，向服务器写入数据
            OutputStream outputStream = httpURLConnection.getOutputStream();
            outputStream.write(data);

            int response = httpURLConnection.getResponseCode(); // 获得服务器的响应码
            L.e("mainASDFGHJ","responseCode = " + response);
            if (response == HttpURLConnection.HTTP_OK) {
                InputStream is = httpURLConnection.getInputStream();
                byte[] bytes = getBytes(is);
                String str = new String(bytes);
//                Thread.sleep(5000);//TODO:模仿网络慢的情况
                return str;
            } else if (response == HttpURLConnection.HTTP_NOT_FOUND){
                return JsonMessage.HttpNotFund;
            }else {
                return JsonMessage.ResponseWrong;
            }
        } catch (MalformedURLException e){  //URL格式或者路径错误异常
            return JsonMessage.MalfError;
        } catch (IOException e) {   //网络异常
            return JsonMessage.IOError;
        }catch (Exception e) { //普通异常
            return JsonMessage.Error;
        }
    }
    /**
     * 将流数据转换成二进制数据
     * @param is
     * @return
     * @throws Exception
     */
    private static byte[] getBytes(InputStream is) throws Exception {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = is.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        is.close();
        bos.flush();
        byte[] result = bos.toByteArray();
        return result;
    }

    /**
     * 获取封装好的请求体信息
     * @param params
     * @param encode
     * @return
     */
    private static StringBuffer getRequestData(Map<String, Object> params, String encode) {

        StringBuffer stringBuffer = new StringBuffer(); // 存储封装好的请求体信息
        try {
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                stringBuffer.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue().toString(), encode)).append("&");
            }
            if (params.size() > 0) {
                stringBuffer.deleteCharAt(stringBuffer.length() - 1); // 删除最后的一个"&"
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return stringBuffer;
    }

    public static String getAuthCode(Context context) {
        // 在这里写authCode算法
        String token = BaseActivity.getToken(context);
        L.e("mainHHH","get token = " + token);
        String characteristic = BaseActivity.getCharacteristic(context);
        String origin = BaseActivity.getOrigin();
        String guid = UUID.randomUUID() + "";
        L.e("mainGuid","guid = " + guid);
        String time = (new Date().getTime() + 8 * 3600 * 1000) + "";
        String sign = CommonUtil.MD5("" + token + "|" + guid + "|" + time + "|" + origin + "|" + characteristic + "|" + ConstantsValue.AuthCode_key + "").toUpperCase();
        String authCode = "" + token + "|" + guid + "|" + time + "|" + origin + "|" + characteristic + "|" + sign + "";
        return authCode;
    }

    public static String getWebsite_cdn() {
        return IotServerConfig.getCDNServerRoot();
    }

    /**
     * 获取指定版本app的下载路径
     * @param id
     * @return
     */
    public static String getUrlAssignApp(String id) {
        return IotServerConfig.getCDNServerRoot() + "app/version/" + id + ".apk";
    }
}
